package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendmsg(@RequestBody User user) {

        String phone = user.getPhone();
        log.info(phone);
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码为:{}", code);

            request.getSession().setAttribute(phone, code);
            return R.success("验证码发送成功!");
        }
        return R.error("验证码发送失败!");
    }

    /**
     * 移动端用户登录
     *
     * @param map
     * @param
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map map) {

        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        Object codeinsession = request.getSession().getAttribute(phone);

        if (codeinsession != null && codeinsession.equals(code)) {

            LambdaQueryWrapper<User> userlqw = new LambdaQueryWrapper<>();
            userlqw.eq(User::getPhone, phone);
            User user = userService.getOne(userlqw);

            if (user == null) {
                User user1 = new User();
                user1.setPhone(phone);
                user1.setStatus(1);
                userService.save(user1);
            }
            request.getSession().setAttribute("user", user.getId());
            return R.success(user);
        }
        return R.error("登录失败!");
    }

    @PostMapping("loginout")
    public R logout() {
        request.getSession().removeAttribute("user");
        return R.success("退出成功!");
    }
}
